let departmentlistModule = (function(){
    let $tbody = $('tbody');
    // 动态渲染页面
    async function bindHTML(){
        // let result = await axios.get('/department/list');
        let result = await queryDepartment();// 本地缓存
        if(result.code != 0)  return;
        let str = '';
        result.data.forEach(data=>{
            let {
                id,
                name,
                desc
            } = data;
            str += `<tr>
            <td class="w10">${id}</td>
            <td class="w20">${name}</td>
            <td class="w40">${desc}</td>
            <td class="w20" departmentId=${id} departmentName=${name}>
                <a href="javascript:;">编辑</a>
                <a href="javascript:;">删除</a>
            </td>
        </tr>`
        })
        $tbody.html(str)
    }
    // 编辑 删除 功能
    function handle(){
        // 基于事件委托
        $tbody.click(async e =>{
            let target = e.target,
                $target = $(target),
                tagName = target.tagName,
                TEXT = $target.html();
            let id = $target.parent().attr('departmentId');
            let name = $target.parent().attr('departmentName');
            if(tagName === 'A'){
                if(TEXT === '编辑'){
                    // 跳转页面
                    window.location.href = `departmentadd.html?departmentId=${id}`
                    return;
                }else if(TEXT === '删除'){
                    // 删除前的确认
                    let flag = confirm(`小主，您确定要删除【${name}】吗？`);
                    if(!flag) return;
                    let result = await axios.get('/department/delete',{
                        params:{
                            departmentId:id 
                        }
                    })
                    if(result.code == 0){
                        alert(`小主，已成功为您删除一个【${name}】~`);
                        // 把被删除的部门从列表中移除
                        $target.parent().parent().remove()
                        return;
                    }
                    alert('小主，网络繁忙，请稍后重试');
                    return;
                }
            }
        })

    }
    return {
        init(){
            bindHTML();
            handle();
        }
    }
}())
departmentlistModule.init();